/********************************************************************
	created:	2012/4/8
	filename: 	TiledSolidGeometry.cpp
	author:		Mwolf
	
	purpose:	
*********************************************************************/

#include "stdafx.h"
#include "TiledSolidGeometry.h"

#include "GWCommon.h"
#include "DebugDraw.h"

typedef struct StageGeomListType
{
	STAGE_GEOM*				StageGeomHead;
	STAGE_GEOM*				StageGeomTail;
	int						geom_count;
} STAGE_GEOM_LIST;

static STAGE_GEOM_LIST StageGeomList = { NULL, NULL, 0 };

// Stage geometry methods
STAGE_GEOM* StageGeom_Create()
{
	STAGE_GEOM* geom = new STAGE_GEOM();
	geom->next = NULL;

	if (StageGeomList.StageGeomTail == NULL)
	{
		// Build new linked list
		StageGeomList.StageGeomHead = geom;
		StageGeomList.StageGeomTail = geom;
	}
	else
	{
		// Add new geometry to the tail
		StageGeomList.StageGeomTail->next = geom;
		StageGeomList.StageGeomTail = geom;
	}

	StageGeomList.geom_count++;

	return geom;
}

STAGE_GEOM* StageGeom_GetFirst()
{
	return StageGeomList.StageGeomHead;
}

STAGE_GEOM* StageGeom_GetNext(STAGE_GEOM* geom)
{
	return geom->next;
}

int StageGeom_GetCount()
{
	return StageGeomList.geom_count;
}

void StageGeom_RemoveAll()
{
	STAGE_GEOM* geom;
	for (geom = StageGeom_GetFirst(); geom != NULL; )
	{
		STAGE_GEOM* old_geom = geom;
		geom = StageGeom_GetNext(geom);
		delete old_geom;
	}

	StageGeomList.StageGeomHead = NULL;
	StageGeomList.StageGeomTail = NULL;
	StageGeomList.geom_count = 0;
}

void StageGeom_DebugRender( STAGE_GEOM* geom, GWColor color /*= GWColor::YELLOW */ )
{
	if (geom->tile_type_id != -1)
	{
		//Debug_DrawBoundingBox( geom->post_proj_bound_last_frame, GWColor::RED, -.01f );
		DebugDrawList_DrawBoundingBox( geom->post_proj_bound, color, -.01f );
	}
}

bool StageGeom_Remove( STAGE_GEOM* to_remove )
{
	if ( !to_remove ) return false;

	STAGE_GEOM* geom = StageGeom_GetFirst();
	STAGE_GEOM* last;

	// Bail if list empty
	if ( !geom ) return false;

	// Remove header
	if ( geom == to_remove )
	{
		StageGeomList.StageGeomHead = geom->next;

		// There is only one element in the list, make tail NULL
		if ( StageGeomList.StageGeomTail == geom )
			StageGeomList.StageGeomTail = NULL;

		last = geom;
		geom = StageGeom_GetNext( geom );
	}

	while ( geom )
	{
		if ( geom == to_remove )
		{
			last->next = geom->next;

			// Move back tail if we just removed it
			if ( StageGeomList.StageGeomTail == geom )
				StageGeomList.StageGeomTail = last;

			delete geom;

			return true;
		}

		last = geom;
		geom = StageGeom_GetNext( geom );
	}

	// Not found
	return false;
}
